package test06;


import java.util.ArrayList;
import java.util.List;

/**
 * 推理调度器（上下文类）
 */
public class InferenceScheduler {
    private InferenceOptimizationStrategy currentStrategy;
    private Model model;
    private PerformanceMetrics metrics;

    public InferenceScheduler(Model model) {
        this.model = model;
        this.metrics = new PerformanceMetrics();
        this.currentStrategy = new QuantizationStrategy(); // 默认策略
    }

    public void setStrategy(InferenceOptimizationStrategy strategy) {
        this.currentStrategy = strategy;
        System.out.println("🔄 切换优化策略: " + strategy.getClass().getSimpleName());
    }

    public Tensor[] executeInference(RequestData[] requests) {
        System.out.println("\n🎯 开始执行推理任务");
        System.out.println("请求数量: " + requests.length);

        long startTime = System.currentTimeMillis();

        // 委托给当前策略执行优化推理
        Tensor[] results = currentStrategy.optimizeInference(model, requests);

        long endTime = System.currentTimeMillis();

        // 更新性能指标
        double latency = endTime - startTime;
        double throughput = (double) requests.length / (latency / 1000);
        metrics.updateMetrics(latency, throughput, 1024.0);

        System.out.println("✅ 推理完成");
        System.out.println(metrics);

        return results;
    }

    public void autoSelectStrategy(WorkloadProfile workload) {
        System.out.println("\n🤖 自动策略选择基于工作负载:");
        workload.analyzeCurrentLoad();

        if (workload.getRequestRate() > 1000 && workload.getLatencySLA() > 50) {
            // 高吞吐量场景
            CompositeOptimizationStrategy composite = new CompositeOptimizationStrategy();
            composite.addStrategy(new QuantizationStrategy());
            composite.addStrategy(new DynamicBatchingStrategy());
            setStrategy(composite);
            System.out.println("选择: 量化 + 动态批处理 (高吞吐量模式)");
        } else if (workload.getLatencySLA() < 20) {
            // 低延迟场景
            setStrategy(new QuantizationStrategy());
            System.out.println("选择: 量化策略 (低延迟模式)");
        } else if (workload.getRequestRate() < 100) {
            // 交互式场景
            setStrategy(new ContinuousBatchingStrategy());
            System.out.println("选择: 连续批处理 (交互式模式)");
        } else {
            // 默认策略
            CompositeOptimizationStrategy composite = new CompositeOptimizationStrategy();
            composite.addStrategy(new QuantizationStrategy());
            composite.addStrategy(new KernelFusionStrategy());
            setStrategy(composite);
            System.out.println("选择: 量化 + 内核融合 (平衡模式)");
        }
    }

    // Getters
    public PerformanceMetrics getMetrics() { return metrics; }
}
